<template>
  <div class="image-loader-container">
    <img
      v-if="!allDone"
      :src="placeholder"
      class="placeholder"
    >
    <img
      :src="src"
      :style="{opacity: imageLoaded ? 1 : 0, transition: `${duration}ms`}"
      @load="handlerLoad"
    >
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
      required: true,
    },
    duration: {
      type: Number,
      default: 500,
    },
  },
  data() {
    return {
      imageLoaded: false, // 原图是否加载完成
    };
  },

  computed: {
    // 是否所有图片都已加载完成，用于解决 显示原图隐藏占位图时，两者切换时存在的空白时间
    allDone() {
      return this.imageLoaded ? true : false;
    },
  },
  methods: {
    handlerLoad() {
      setTimeout(() => {
        this.imageLoaded = true;
        this.$emit("load");
      }, this.duration);
    },
  },
};
</script>

<style scoped lang="less">
@import "~@/style/minix.less";
.image-loader-container {
  width: 100%;
  height: 100%;
  position: relative;
  img {
    object-fit: cover;
    .self-fill();
  }
  .placeholder {
    // 占位图 模糊
    filter: blur(2vw);
  }
}
</style>